package com.bowlong.io;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;

import com.bowlong.text.Encoding;
import com.bowlong.util.DateEx;

public class URLCache {

	URL url;
	byte[] buff;
	String text;

	long lastTm = 0; // 最后获取时间
	long timeout = 5 * DateEx.TIME_MINUTE; // 超时时间(默认5分钟)

	public URLCache(String url) throws MalformedURLException {
		this(new URL(url), 5 * DateEx.TIME_MINUTE);
	}

	public URLCache(URL url) {
		this(url, 5 * DateEx.TIME_MINUTE);
	}

	public URLCache(String url, long timeout) throws MalformedURLException {
		this(new URL(url), timeout);
	}

	public URLCache(URL url, long timeout) {
		this.url = url;
		this.timeout = timeout;
	}

	private boolean isTimeout() {
		return lastTm + timeout < System.currentTimeMillis();
	}

	public byte[] getData() throws MalformedURLException, IOException {
		if (isTimeout()) {
			this.buff = FileEx.readFully(url);
			this.lastTm = System.currentTimeMillis();
			this.text = null;
		}

		return this.buff;
	}

	public String getText() throws IOException {
		final Charset charset = Encoding.UTF8;
		return getText(charset);
	}
	
	public String getText(final Charset charset) throws IOException {
		if (text == null) {
			text = new String(getData(), charset);
		}
		return text;
	}

}
